package com.phone.wxtoken;

import com.phone.utils.TextUtil;
import org.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.Date;

/**
 * Created by tisen on 2017/8/29.
 */
public class CommonUtil {

    private static final String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
            "&appid=APPID&secret=APPSECRET";


    public static StringBuffer httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
            TrustManager[] tm = {new PX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
            httpsURLConnection.setDoOutput(true);
            httpsURLConnection.setDoInput(true);

            httpsURLConnection.setRequestMethod("GET");

            InputStream inputStream = httpsURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpsURLConnection.disconnect();
        } catch (ConnectException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static Token getToken(String appid, String appsecret) throws Exception {
        Token token = null;
        String requestUrl = tokenUrl.replace("APPID", appid).replace("APPSECRET", appsecret);
        System.out.println(requestUrl);
        StringBuffer stringBuffer = httpsRequest(requestUrl, "GET", null);
        JSONObject jsonObject = new JSONObject(stringBuffer.toString());
        if (jsonObject != null) {
            System.out.println(jsonObject);
            if (!TextUtil.textIsEmpty(jsonObject.optString("access_token"))) {
                System.out.println("success " + new Date());
                token = new Token(jsonObject.optString("access_token"), jsonObject.optInt("expires_in"));
            } else {
                System.out.println("error " + new Date());
                TokenError error = new TokenError(jsonObject.optString("errcode"), jsonObject.optString("errmsg"));
                throw new TokenException(error);
            }
        }
        return token;
    }
}
